<template>
  <div class="app-container">
    <!-- 筐管理 -->

    <el-row :gutter="24">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80">
            <el-form-item label="筐编号" prop="crateCode">
              <el-input
                v-noSpace
                v-model="queryParams.crateCode"
                placeholder="请输入筐编号"
                clearable
                class="!w-[192px]"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="筐名称" prop="crateName">
              <el-input
                v-noSpace
                v-model="queryParams.crateName"
                placeholder="请输入筐名称"
                clearable
                class="!w-[192px]"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="类型" prop="type">
              <el-select
                v-model="queryParams.type"
                placeholder="请输入类型"
                clearable
                class="!w-[192px]"
                @change="handleQuery"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请输入状态"
                clearable
                class="!w-[192px]"
                @change="handleQuery"
              >
                <el-option
                  v-for="item in assetStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="开始时间" prop="createTimeStart">
              <el-date-picker
                v-model="queryParams.createTimeStart"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="结束时间" prop="createTimeEnd">
              <el-date-picker
                v-model="queryParams.createTimeEnd"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择日期"
              />
            </el-form-item> -->

            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              <el-button
                icon="Plus"
                type="success"
                @click="handleAdd({}, 'add')"
                v-hasPerm="'sys:basketManagement:edit'"
              >
                新增筐
              </el-button>
              <!-- <el-button :disabled="exportIds.ids.length == 0" type="success" @click="handleExport">
                一键清洗{{ exportIds.ids.length == 0 ? "" : exportIds.ids.length + "个脏筐" }}
              </el-button> -->
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never">
          <el-table
            v-loading="loading"
            show-overflow-tooltip
            :tooltip-formatter="tableRowFormatter"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" :selectable="handleDisable" width="55" />
            <el-table-column prop="code" label="筐编号" />
            <el-table-column prop="name" label="筐名称" />
            <el-table-column prop="type" label="类型">
              <template #default="scope">
                <div>
                  {{ typeFormat(scope.row.type) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="batchNo" label="批次号" />

            <el-table-column prop="capacityL" label="容量" />
            <el-table-column prop="remarks" label="备注" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <div>
                  {{ statusFormat(scope.row.status) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="280" fixed="right">
              <template #default="scope">
                <el-button
                  size="small"
                  link
                  type="primary"
                  @click.stop="handleAdd(scope.row, 'edit')"
                  v-hasPerm="'sys:basketManagement:edit'"
                >
                  修改
                </el-button>
                <el-button
                  size="small"
                  link
                  type="primary"
                  @click.stop="handleAdd(scope.row, 'info')"
                >
                  查看
                </el-button>
                <el-button
                  size="small"
                  link
                  type="danger"
                  @click.stop="handleDelete(scope.row)"
                  v-hasPerm="'sys:basketManagement:del'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-model="dialogVisible.visible"
      :title="dialogVisible.title"
      width="1000px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormDataRef"
        :disabled="dialogVisible.type == 'info' ? true : false"
        :model="dialogFormData"
        :rules="rules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="筐名称" prop="name">
              <el-input
                v-noSpace
                v-model="dialogFormData.name"
                :maxlength="20"
                placeholder="请输入筐名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="type">
              <el-select
                v-model="dialogFormData.type"
                placeholder="请输入类别"
                style="width: 250px"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="长度(厘米)" prop="lengthCm">
              <el-input
                v-noSpace
                v-model.number="dialogFormData.lengthCm"
                placeholder="请输入长度(厘米)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宽度(厘米)" prop="widthCm">
              <el-input
                v-noSpace
                v-model.number="dialogFormData.widthCm"
                placeholder="请输入宽度(厘米)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高度(厘米)" prop="heightCm">
              <el-input
                v-noSpace
                v-model.number="dialogFormData.heightCm"
                placeholder="请输入高度(厘米)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="容量(升)" prop="capacityL">
              <el-input
                v-noSpace
                v-model.number="dialogFormData.capacityL"
                placeholder="请输入容量(升)"
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="批次号" prop="batchNo">
              <el-input v-noSpace v-model.number="dialogFormData.batchNo" placeholder="请输入批次号" />
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="筐状态" prop="status">
              <el-select v-model="dialogFormData.status" placeholder="请输入筐状态">
                <el-option
                  v-for="item in assetStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-noSpace
                v-model="dialogFormData.remarks"
                :maxlength="200"
                :rows="4"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <span class="dialog-footer df">
              <el-button @click="dialogVisible.visible = false">取 消</el-button>
              <el-button v-debounce="handleSave" type="primary">提 交</el-button>
            </span>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import basketManagementAPI, {
  basketManagementPageQuery,
  basketManagementPageVO,
} from "@/api/assetManagement/basketManagement";
import configApi, { ConfigType } from "@/api/config/config";
import { FormItemRule } from "element-plus/es";
import { tableRowFormatter } from "@/utils/index";
defineOptions({
  name: "User",
  inheritAttrs: false,
});
// 加载loading
const loading = ref(false);
// 分页总数
const total = ref(0);
// 搜索ref
const queryFormRef = ref(ElForm);
// 一级弹窗ref
const dialogFormDataRef = ref(ElForm);
//一级弹窗
const dialogVisible = reactive({
  visible: false,
  title: "",
  type: "",
});
//一级表单验证
const rules = reactive<Record<string, FormItemRule[]>>({
  name: [{ required: true, message: "请输入筐名称", trigger: "blur" }],
  type: [{ required: true, message: "请输入类型", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  // batchNo: [{ required: true, message: "请输入批次号", trigger: "blur" }],
  // model: [{ required: true, message: "请输入型号", trigger: "blur" }],
  // unit: [{ required: true, message: "请输入计量单位", trigger: "blur" }],
  // value: [{ required: true, message: "筐价值是必填项", trigger: "blur" }],
  // purchaseDate: [{ required: true, message: "请选择购置日期", trigger: "change" }],
  // usageYears: [{ required: true, message: "使用年限是必填项", trigger: "blur" }],
  // usePosition: [{ required: true, message: "请输入存放位置", trigger: "blur" }],
});
// 查询参数
const queryParams = reactive<basketManagementPageQuery>({
  pageNum: 1,
  pageSize: 10,
});
//状态
const assetStatusList = ref([
  {
    label: "使用中",
    value: 0,
  },
  {
    label: "干净闲置",
    value: 1,
  },
  {
    label: "损坏",
    value: 2,
  },
  {
    label: "报废",
    value: 3,
  },
  {
    label: "赃筐",
    value: 4,
  },
]);

// 类型
const typeList = ref([
  {
    label: "干货",
    value: 0,
  },
  {
    label: "水产",
    value: 1,
  },
]);
const typeFormat = (val: number) => {
  return typeList.value.find((item) => item.value == val)?.label;
};
const statusFormat = (val: number) => {
  return assetStatusList.value.find((item) => item.value == val)?.label;
};

// 一级==列表参数
const pageData = ref<basketManagementPageVO[]>();
// 查询函数
const handleQuery = () => {
  loading.value = true;
  console.log("queryParams", queryParams);
  // if (queryParams.status) {
  //   queryParams.status = [queryParams.status] as any;
  // }

  basketManagementAPI
    .getPage(queryParams)
    .then((data) => {
      console.log(data);
      pageData.value = [...(data?.list as any)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 一级==新增表单参数
const dialogFormData: basketManagementPageVO = reactive({
  name: "", // 筐名称
  type: "", // 类型
  status: 1, //状态
  lengthCm: "", //长度(厘米)
  widthCm: "", // 宽度(厘米)
  heightCm: "", //高度(厘米)
  capacityL: "", //容量(升)
  batchNo: "", //批次号
  remarks: "", //备注
});

//一级弹窗=== 新增筐
const handleAdd = (row: any, type: any) => {
  if (type == "add") {
    dialogVisible.visible = true;
    dialogVisible.title = "新增筐";
    dialogVisible.type = "add";
    delete dialogFormData.code;
    delete dialogFormData.id;
  } else if (type == "edit") {
    dialogVisible.visible = true;
    dialogVisible.title = "修改筐";
    dialogVisible.type = "edit";
    let data = { ...row };
    data.crateCode = data.code;
    nextTick(() => {
      Object.assign(dialogFormData, { ...data });
    });
  } else {
    dialogVisible.visible = true;
    dialogVisible.title = "查看筐";
    dialogVisible.type = "info";
    let data = { ...row };
    nextTick(() => {
      Object.assign(dialogFormData, { ...data });
    });
  }
};
// 筐删除操作
function handleDelete(row: any) {
  ElMessageBox.confirm("确定要删除该筐吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log("删除", row);
      // 实现删除逻辑
      basketManagementAPI
        .delete({ id: row.id })
        .then((data) => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .catch((error) => {
          loading.value = false;
          //ElMessage.error(`${error}`); //注释报错弹窗
        });
    })
    .catch(() => {
      // 取消删除
    });
}
//一级弹窗===新增筐关闭
const handleCloseDialog = () => {
  console.log(dialogFormDataRef);
  dialogVisible.visible = false;
  dialogFormDataRef.value?.clearValidate();
  dialogFormDataRef.value?.resetFields();
};
//新增/修改保存==筐
const handleSave = () => {
  loading.value = true;
  console.log(dialogFormData);
  // 实现新增/修改逻辑
  dialogFormDataRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    const apiCall =
      dialogVisible.type === "add" ? basketManagementAPI.add : basketManagementAPI.update;
    apiCall(dialogFormData)
      .then((data) => {
        console.log(data);
        loading.value = false;
        dialogVisible.visible = false;
        ElMessage.success("保存成功");
        handleQuery();
      })
      .catch((error) => {
        loading.value = false;
        //ElMessage.error(`${error}`); //注释报错弹窗
      });
  });
};

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  // queryParams.deptId = undefined;
  // queryParams.createTime = undefined;
  handleQuery();
}
interface ExportIds {
  ids: string[];
}
const exportIds: ExportIds = reactive({
  ids: [],
});
const handleSelectionChange = (selection: any[]) => {
  exportIds.ids = selection.map((item) => item.id);
  console.log(exportIds);
  // selectedCount.value = selection.length;
};
const handleExport = () => {
  loading.value = true;
  // 实现导出逻辑
  basketManagementAPI
    .batchClean(exportIds)
    .then((data) => {
      ElMessage.success("清洗成功");
      handleQuery();
    })
    .catch((error) => {
      loading.value = false;
      //ElMessage.error(`${error}`); //注释报错弹窗
    });
};
const handleDisable = (row: any) => {
  return [4].includes(row.status);
};
onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
